package com.soho.helper;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;

import com.jfinal.kit.HashKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Record;

public class UtilsHelper {

	public static String md5(String str){
		return HashKit.md5(str+"jz");
	}
	
	public static String getParam(HttpServletRequest request,String key){
		return request.getParameter(key);
	}
	
	public static Kv success(Object info){
		return Kv.create().set("code", ContentHelper.STATUS_SUCCESS).set("data", info);
	}
	public static Kv success(Object info,int status){
		return Kv.create().set("code", status).set("data", info);
	}
	
	public static Kv error(Object info){
		return Kv.create().set("code", ContentHelper.STATUS_FAILS).set("errmsg", info);
	}
	public static Kv error(Object info,int status){
		return Kv.create().set("code", status).set("errmsg", info);
	}
	
	public static void returnJson(HttpServletResponse response,Kv params){
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		// Get the printwriter object from response to write the required json object to the output stream      
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// Assuming your json object is **jsonObject**, perform the following, it will return your json object  
		out.print(JsonKit.toJson(params));
		out.flush();
	}
	
	public static boolean checkIsEmpty(Object obj){
		if(obj instanceof Map){
			return ((Map<?, ?>) obj).size()==0;
		}
		if(obj == null){
			return true;
		}
		if(Objects.isNull(obj)){
			return true;
		}
		if(obj instanceof List){
			return ((List<?>) obj).size()==0;
		}
		if(StringUtils.isEmpty(obj.toString())){
			return true;
		}
		return false;
	}
	
	public static String geneterRamdomStr(int len){
		return RandomStringUtils.randomAlphabetic(len).toUpperCase();
	}
	
	public static Date Now(){
		return new Date();
	}
	
	public static String getYmd(){
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		return df.format(UtilsHelper.Now());
	}
	
	public static String getYm(){
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM");
		return df.format(UtilsHelper.Now());
	}
	

	public static String hideCardNo(String _card_no){
		return _card_no.replaceAll("\\d*(\\d{4})$","***************$1");
	}
	
	//检查Code 返回值
	public static boolean isFails(Kv _map){
		return _map.getInt("code")!=ContentHelper.STATUS_SUCCESS;
	}
	
	public static String getBeforeDate(){
		Calendar calendar 	=	Calendar.getInstance();
		calendar.add(Calendar.MONTH, -1);
        Date lastMonth = calendar.getTime(); //结果    
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");  
        return sf.format(lastMonth);  
	}
	
	public static void main(String[] args) {
		//MPrint.print(hideCardNo("6217002710000684874"));
		PrintHelper.print(getBeforeDate());
	}
	
	public static double formatNumber(String _money){
		return new BigDecimal(_money).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
	}
	
	public static double formatNumber(String _money,int limit){
		return new BigDecimal(_money).setScale(limit,BigDecimal.ROUND_HALF_UP).doubleValue();
	}
	
	public static double dev(long base,double devValue){
		return BigDecimal.valueOf(base).divide(BigDecimal.valueOf(devValue),2,BigDecimal.ROUND_HALF_UP).doubleValue();
	}
	
	public static double dev(long base,double devValue,int limit){
		return BigDecimal.valueOf(base).divide(BigDecimal.valueOf(devValue),limit,BigDecimal.ROUND_HALF_UP).doubleValue();
	}
	
	
	public static String getValueFromKv(Kv _kv,String _key,String _default_value){
		String _value	=	_kv.getStr(_key);
		return UtilsHelper.checkIsEmpty(_value)?_default_value:_value;
	}
	public static String getValueFromKv(Kv _kv,Long _key,String _default_value){
		String _value	=	_kv.getStr(_key);
		return UtilsHelper.checkIsEmpty(_value)?_default_value:_value;
	}
	
	public static Kv getLimitInfo(List<Record> lst,int _perpage,int _page){
	    int _totalRow				= lst.get(0).getInt("count");
	    int _tmpTotalPage			= _totalRow%_perpage;
	    int _totalPage				= _tmpTotalPage>0?_totalRow/_perpage+1:_totalRow/_perpage;
	    int _tmpPage				= _page>1?_page-1:0;
	    String _limit				= "limit "+_tmpPage*_perpage+","+_perpage;
	    return Kv.by("total_page", _totalPage).set("limit", _limit);
	}
	
	public static void cors(HttpServletResponse response) {
		response.addHeader("Access-Control-Allow-Origin", "*");
		response.addHeader("Access-Control-Allow-Credentials", "true");
		response.addHeader("Access-Control-Allow-Methods","*"); //使用通配符
		response.addHeader("Access-Control-Allow-Headers","*");  //使用通配符
	}
	
	
}
